<?php
/**
 * Created by Sublime.
 * Author: lingyun
 * Date: 2017-12-07 15:24:31
 * @desc 微信支付类
 */
namespace app\comm\service;
use think\Controller;
use think\Db;
use think\db\Query;
use controller\BasicAdmin;
use service\DataService;
use service\LogService;
use service\PayService;
use Wechat\WechatPay;
use Wechat\Lib\Tools;
class WeixinpayService extends Controller{
    /**
     * 生成测试支付二维码
     * @return \think\response\Json
     */
    public function _pay_payqrc($post)
    {
        $pay = &load_wechat('pay');     //获取配置信息
        if(!$this->isPay($post['order_sn'])){
            return json_encode(['code' => 0,'msg'=>'该订单已经支付，请勿重复支付','order_sn' => $post['order_sn']]);
        }
        // 订单号未支付，生成支付二维码URL
        $url = PayService::createWechatPayQrc($pay, $post['order_sn'], $post['final_amount']*100, '微信扫码支付测试!');
        if ($url !== false) {
            return json_encode(['code' => 1, 'url' => $url, 'order_sn' => $post['order_sn']]);
        }
        return json_encode(['code'=>0,'msg'=>"生成支付二维码失败, {$pay->errMsg}[{$pay->errCode}]"]);
    }
    /**
     * 微信支付
     * @Author   lingyun
     * @DateTime 2017-12-08T15:58:34+0800
     * @return   [type]                   [description]
     */
    public function weixin_pay($post){
        $pay = &load_wechat('pay');     //获取配置信息
        if(!$this->isPay($post['order_sn'])){
            return json_encode(['code' => 0,'msg'=>'该订单已经支付，请勿重复支付','order_sn' => $post['order_sn']]);
        }
        $config['appid'] = sysconf('wechat_appid');       //appid
        $config['mch_id'] = sysconf('wechat_mch_id');
        $config['partnerkey'] = sysconf('wechat_partnerkey');
        $pay = new WechatPay($config); 
        // var_dump($config);   
        // var_dump($post);        
        $prepayid = PayService::createWechatPayJsPicker($pay, $post['openid'], $post['order_sn'], $post['final_amount'],'订单支付');
       // var_dump($prepayid); 
        if($prepayid !== false){
            // $nonceStr = Tools::createNoncestr();
            // halt($prepayid);
            // $data=array(
            //     'appid'=>$config['appid'],  //appid
            //     'timestamp'=>strval(time()), //时间戳
            //     'noncestr'=>$nonceStr,      // 随机字符串
            //     'package'=>'prepay_id='.$prepayid,// 预支付交易会话标识
            //     'signtype'=>'MD5'//加密方式
            // );

            $prepayid['sign'] = Tools::getPaySign($prepayid,$config['partnerkey']);
            return $prepayid;
        }else{
            return false;
        }
    }

    /**
     * 向支付平台查询订单状态
     * @Author   lingyun
     * @DateTime 2017-12-08T15:02:42+0800
     * @return   [type]                   [description]
     */
    public function checkorderstatus($order_sn){
        $postdata['appid'] = sysconf('wechat_appid');       //appid
        $postdata['mch_id'] = sysconf('wechat_mch_id');
        $postdata['partnerkey'] = sysconf('wechat_partnerkey');
        $postdata['out_trade_no'] = $order_sn;
        $obj = new WechatPay($postdata);
        unset($postdata['partnerkey']);
        $result = $obj->getArrayResult($postdata,"https://api.mch.weixin.qq.com/pay/orderquery");
        if (empty($result)) {
            return ['code'=>0,'msg'=>'解析返回结果失败'];
            // $this->error('解析返回结果失败',url('Index/index'));
        }
        if ($result['return_code'] !== 'SUCCESS') {
            return ['code'=>0,'msg'=>$result['return_msg']];
            // $this->error('解析返回结果失败',url('Index/index'));
        }
        if (isset($result['err_code']) && $result['err_code'] !== 'SUCCESS') {
            return ['code'>0,'msg'=>$result['err_code_des']];
            // $this->error($result['err_code_des'],url('Index/index'));
        }
        return ['code'=>1,'msg'=>'支付成功'];
        // $this->success('支付成功',url('Index/index'));
    }

    /**
     * @Author  lingyun
     * @Desc    微信刷卡支付查询订单状态
     * @param $order_sn
     * @return array
     */
    public function get_shuaka_order($order_sn){
        $postdata['appid'] = sysconf('wechat_appid');       //appid
        $postdata['mch_id'] = sysconf('wechat_mch_id');
        $postdata['partnerkey'] = sysconf('wechat_partnerkey');
        $postdata['out_trade_no'] = $order_sn;
        $obj = new WechatPay($postdata);
        unset($postdata['partnerkey']);
        $result = $obj->getArrayResult($postdata,"https://api.mch.weixin.qq.com/pay/orderquery");
        if($result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS"){
            //支付成功
            if($result["trade_state"] == "SUCCESS"){
                $succCode = 1;
                return ['result'=>$result,'succCode'=>$succCode];
            }else if($result["trade_state"] == "USERPAYING"){
                $succCode = 2;
                return ['result'=>false,'succCode'=>$succCode];
            }
        }
        //如果返回错误码为“此交易订单号不存在”则直接认定失败
        if(isset($result["err_code"]) &&  $result['err_code'] == "ORDERNOTEXIST")
        {
            $succCode = 0;
        }else{
            //如果是系统错误，则后续继续
            $succCode = 2;
        }
        return ['result'=>$result['trade_state_desc'],'succCode'=>$succCode];
    }

    /**
     * 判断订单是否已经支付
     * @Author   lingyun
     * @DateTime 2017-12-07T20:54:31+0800
     * @return   boolean                  [description]
     */
    public function isPay($order_sn){
        $res = Db::name('order')->where('order_sn',$order_sn)->value('pay_status');     //订单支付状态
        if($res == 1){      //已支付
            return false;
        }else{
            return true;
        }
    }

}